package com.my.api;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.entity.NightSpot;
import com.my.entity.Setting;
import com.my.entity.UserMonitor;
import com.my.service.NightSpotService;
import com.my.service.SettingService;
import com.my.service.UserMonitorService;
import com.my.service.UserService;
import com.my.util.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("api")
@CrossOrigin
public class NightSpotApiController {

    @Autowired
    private NightSpotService service;

    @Autowired
    private SettingService sService;

    @Autowired
    private UserMonitorService monitorService;

    @Autowired
    private UserService uService;

    @PostMapping("nightSpot/add")
    public Rest add(Long userId) {
        Setting setting = sService.getOne(new QueryWrapper<Setting>().eq("setting_key", "nightSpotStartTime"));
        DateTime dateTime = DateUtil.parse(DateUtil.format(new Date(), "yyyy-MM-dd ") + setting.getSettingValue(), "yyyy-MM-dd HH:mm");
        long currentTime = System.currentTimeMillis();
        if(!(currentTime > DateUtil.offsetMinute(dateTime, -10).getTime() && currentTime < dateTime.getTime())) {
            return Rest.ok("签到无效，不在签到时间内");
        }
        if(service.save(new NightSpot().setUserId(userId).setRemarks("正常晚点签到！"))) {
            return Rest.ok("签到成功！");
        }
        return Rest.err("签到失败！");
    }

    @GetMapping("nightSpot")
    public Rest nightSpot(Long userId, Long classId, Boolean confirm) {
        if(userId != null) {
            UserMonitor monitor = monitorService.getOne(new QueryWrapper<UserMonitor>().eq("user_id", userId).eq("type", 2));
            if(monitor != null) {
                userId = null;
                classId = monitor.getGradeClassId();
            }
        }
        Integer userType = null;
        if(userId != null) {
            userType = uService.getById(userId).getType();
        }
        return Rest.ok().setData("list", service.getApiList(userId, userType, classId, (confirm == null ? true : false)));
    }

    @PostMapping("nightSpot/confirm")
    public Rest confirm(Long id) {
        NightSpot nightSpot = service.getById(id);
        if(service.updateById(nightSpot.setConfirm(true))) {
            return Rest.ok("确认成功！");
        }
        return Rest.err("确认失败！");
    }

}
